<template>
  <div class="ad-container" :id="adId"></div>
</template>

<script setup>
import { ref, onMounted, defineProps } from 'vue';

const props = defineProps({
  adClient: {
    type: String,
    required: true
  },
  adSlot: {
    type: String,
    required: true
  },
  adFormat: {
    type: String,
    default: 'auto'
  },
  adStyle: {
    type: Object,
    default: () => ({
      display: 'block'
    })
  }
});

const adId = ref(`ad-${Math.random().toString(36).substring(2, 15)}`);

const loadAd = () => {
  try {
    // 创建ins元素
    const ins = document.createElement('ins');
    ins.className = 'adsbygoogle';
    ins.style.display = 'block';
    ins.dataset.adClient = props.adClient;
    ins.dataset.adSlot = props.adSlot;
    ins.dataset.adFormat = props.adFormat;
    
    // 应用自定义样式
    Object.keys(props.adStyle).forEach(key => {
      ins.style[key] = props.adStyle[key];
    });
    
    // 查找容器并添加ins元素
    const adContainer = document.getElementById(adId.value);
    if (adContainer) {
      adContainer.appendChild(ins);
      
      // 尝试加载广告
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    }
  } catch (error) {
    console.error('Google AdSense 加载失败:', error);
  }
};

// 加载AdSense脚本
const loadAdScript = () => {
  return new Promise((resolve) => {
    // 如果已经加载过，直接返回
    if (document.querySelector('script[src*="pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"]')) {
      resolve();
      return;
    }
    
    const script = document.createElement('script');
    script.async = true;
    script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
    script.onload = resolve;
    document.head.appendChild(script);
  });
};

onMounted(async () => {
  await loadAdScript();
  loadAd();
});
</script>

<style scoped>
.ad-container {
  width: 100%;
  margin: 15px auto;
  text-align: center;
  overflow: hidden;
}
</style>
